package com.zhanghe.study.study_scala.akka

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

/**
 * Actor间通讯
 *
 * @author zh
 * @date 2021/5/10 11:03
 */
object TestActor {

  def main(args: Array[String]): Unit = {
    val system = ActorSystem("actorFactor")
    val bRef = system.actorOf(Props[ActorB],"b")

    val aRef = system.actorOf(Props(new ActorA(bRef)),"a")
    aRef.!("start")

  }

}

class ActorA(actorRef:ActorRef) extends Actor{

  val actorBRef = actorRef

  override def receive: Receive = {
    case "start" =>
      {
        println("ActorA=> 我要开始出招了")
        self.!("我打")
      }
    case "我打" => {
      println("ActorA=> 佛山无影脚")
      Thread.sleep(3000)
      // 这里要对ActorB发送消息，所以要有ActorB的引用
      actorBRef.!("发动攻击")
    }
    case "发动攻击" =>
    {
      println("ActorA=>我被攻击了")
      self.!("还击")
    }
    case "还击" =>
    {
      println("ActorA=>我要开始还击了")
      self.!("我打")
    }
  }
}

class ActorB() extends Actor{

  var actorRefA : ActorRef = _
  override def receive: Receive = {
    case "发动攻击" =>
    {
      println("ActorB=>我被攻击了")
      // 保存发送者的引用
      actorRefA =  sender()
      self.!("还击")
    }
    case "还击" =>
    {
      println("ActorB=>我要开始还击了")
      self.!("我打")
    }
    case "我打" => {

      println("ActorB=> 铁头功")
      Thread.sleep(3000)
      // 这里要对ActorA发送消息，使用发送者的引用
      actorRefA.!("发动攻击")
    }

  }
}